package com.ldj.tim.server.config;

import com.ldj.tim.common.constant.MqConstants;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author majinhui
 * @description
 * @create 2024/8/29 11:55
 **/
@Configuration
public class MyRabbitConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitTemplate() {
        //投递到交换器失败，数据库记录一下
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("confirm...correlationData-->" + correlationData);
            System.out.println("ack...ack-->" + ack);
            System.out.println("cause...cause-->" + cause);
            if (ack) {
                System.out.println("消息成功投递到交换机");
            } else {
                System.out.println("消息投递到交换机失败: " + cause);
                // todo 在此处处理补偿逻辑
            }
        });

        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("消息投递到队列失败 -> " + message);
            // 这里假设你有一个需要重试的消息
        });
    }


    // 声明一个持久化队列
    @Bean
    public Queue reliableCacheQueue() {
        return QueueBuilder.durable(MqConstants.CACHE_QUEUE)
                .withArgument("x-dead-letter-exchange", MqConstants.DLX_EXCHANGE)
                .withArgument("x-dead-letter-routing-key", MqConstants.DLX_QUEUE_CACHE)
                .build();
    }

    @Bean
    public Queue dlxCacheQueue() {
        return QueueBuilder.durable(MqConstants.DLX_QUEUE_CACHE).build();
    }

    @Bean
    public Queue reliableDurableQueue() {
        return QueueBuilder.durable(MqConstants.QUEUE_DURABLE)
                .withArgument("x-dead-letter-exchange", MqConstants.DLX_EXCHANGE)
                .withArgument("x-dead-letter-routing-key", MqConstants.DLX_QUEUE_CACHE)
                .build();
    }

    @Bean
    public Queue dlxDurableQueue() {
        return QueueBuilder.durable(MqConstants.DLX_QUEUE_DURABLE).build();
    }

    // 声明一个持久化交换机
    @Bean
    public DirectExchange reliableExchange() {
        return new DirectExchange(MqConstants.EXCHANGE_NAME, true, false);
    }
    // 声明一个持久化交换机
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange(MqConstants.DLX_EXCHANGE, true, false);
    }

    // 绑定队列和交换机
    @Bean
    public Binding bindingCache() {
        return BindingBuilder.bind(reliableCacheQueue()).to(reliableExchange()).with(MqConstants.ROUTING_KEY);
    }

    @Bean
    public Binding bindingDurable() {
        return BindingBuilder.bind(reliableDurableQueue()).to(reliableExchange()).with(MqConstants.ROUTING_KEY);
    }
}
